3 * Base class for all skins.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * @defgroup Skins Skins
28 * The main skin class which provides methods and properties for all other skins.
30 * See docs/skin.txt for more information.
34 abstract class Skin
extends ContextSource
{
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
40 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
41 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
43 public $stylename = null;
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
49 static function getSkinNames() {
50 return SkinFactory
::getDefaultInstance()->getSkinNames();
54 * Fetch the skinname messages for available skins.
57 static function getSkinNameMessages() {
59 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
60 $messages[] = "skinname-$skinKey";
66 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
67 * Useful for Special:Preferences and other places where you
68 * only want to show skins users _can_ use.
72 public static function getAllowedSkins() {
75 $allowedSkins = self
::getSkinNames();
77 foreach ( $wgSkipSkins as $skip ) {
78 unset( $allowedSkins[$skip] );
85 * Normalize a skin preference value to a form that can be loaded.
87 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
88 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
90 * @param string $key 'monobook', 'vector', etc.
93 static function normalizeKey( $key ) {
94 global $wgDefaultSkin, $wgFallbackSkin;
96 $skinNames = Skin
::getSkinNames();
98 // Make keys lowercase for case-insensitive matching.
99 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
100 $key = strtolower( $key );
101 $defaultSkin = strtolower( $wgDefaultSkin );
102 $fallbackSkin = strtolower( $wgFallbackSkin );
104 if ( $key == '' ||
$key == 'default' ) {
105 // Don't return the default immediately;
106 // in a misconfiguration we need to fall back.
110 if ( isset( $skinNames[$key] ) ) {
114 // Older versions of the software used a numeric setting
115 // in the user preferences.
121 if ( isset( $fallback[$key] ) ) {
122 $key = $fallback[$key];
125 if ( isset( $skinNames[$key] ) ) {
127 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
130 return $fallbackSkin;
135 * @return string Skin name
137 public function getSkinName() {
138 return $this->skinname
;
142 * @param OutputPage $out
144 public function initPage( OutputPage
$out ) {
145 $this->preloadExistence();
149 * Defines the ResourceLoader modules that should be added to the skin
150 * It is recommended that skins wishing to override call parent::getDefaultModules()
151 * and substitute out any modules they wish to change by using a key to look them up
153 * For style modules, use setupSkinUserCss() instead.
155 * @return array Array of modules with helper keys for easy overriding
157 public function getDefaultModules() {
158 global $wgUseAjax, $wgEnableAPI, $wgEnableWriteAPI;
160 $out = $this->getOutput();
161 $user = $out->getUser();
163 // modules that enhance the page content in some way
165 'mediawiki.page.ready',
167 // modules relating to search functionality
169 // modules relating to functionality relating to watching an article
171 // modules which relate to the current users preferences
175 // Preload jquery.tablesorter for mediawiki.page.ready
176 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
177 $modules['content'][] = 'jquery.tablesorter';
180 // Preload jquery.makeCollapsible for mediawiki.page.ready
181 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
182 $modules['content'][] = 'jquery.makeCollapsible';
185 // Add various resources if required
186 if ( $wgUseAjax && $wgEnableAPI ) {
187 if ( $wgEnableWriteAPI && $user->isLoggedIn()
188 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
189 && $this->getRelevantTitle()->canExist()
191 $modules['watch'][] = 'mediawiki.page.watch.ajax';
194 $modules['search'][] = 'mediawiki.searchSuggest';
197 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
198 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
201 // Crazy edit-on-double-click stuff
202 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
203 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
209 * Preload the existence of three commonly-requested pages in a single query
211 protected function preloadExistence() {
215 $user = $this->getUser();
216 if ( $user->isLoggedIn() ) {
217 $titles[] = $user->getUserPage();
218 $titles[] = $user->getTalkPage();
221 // Check, if the page can hold some kind of content, otherwise do nothing
222 $title = $this->getRelevantTitle();
223 if ( $title->canExist() ) {
224 if ( $title->isTalkPage() ) {
225 $titles[] = $title->getSubjectPage();
227 $titles[] = $title->getTalkPage();
231 // Footer links (used by SkinTemplate::prepareQuickTemplate)
233 $this->footerLinkTitle( 'privacy', 'privacypage' ),
234 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
235 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
242 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
245 $lb = new LinkBatch( $titles );
246 $lb->setCaller( __METHOD__
);
252 * Get the current revision ID
256 public function getRevisionId() {
257 return $this->getOutput()->getRevisionId();
261 * Whether the revision displayed is the latest revision of the page
265 public function isRevisionCurrent() {
266 $revID = $this->getRevisionId();
267 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
271 * Set the "relevant" title
272 * @see self::getRelevantTitle()
275 public function setRelevantTitle( $t ) {
276 $this->mRelevantTitle
= $t;
280 * Return the "relevant" title.
281 * A "relevant" title is not necessarily the actual title of the page.
282 * Special pages like Special:MovePage use set the page they are acting on
283 * as their "relevant" title, this allows the skin system to display things
284 * such as content tabs which belong to to that page instead of displaying
285 * a basic special page tab which has almost no meaning.
289 public function getRelevantTitle() {
290 if ( isset( $this->mRelevantTitle
) ) {
291 return $this->mRelevantTitle
;
293 return $this->getTitle();
297 * Set the "relevant" user
298 * @see self::getRelevantUser()
301 public function setRelevantUser( $u ) {
302 $this->mRelevantUser
= $u;
306 * Return the "relevant" user.
307 * A "relevant" user is similar to a relevant title. Special pages like
308 * Special:Contributions mark the user which they are relevant to so that
309 * things like the toolbox can display the information they usually are only
310 * able to display on a user's userpage and talkpage.
313 public function getRelevantUser() {
314 if ( isset( $this->mRelevantUser
) ) {
315 return $this->mRelevantUser
;
317 $title = $this->getRelevantTitle();
318 if ( $title->hasSubjectNamespace( NS_USER
) ) {
319 $rootUser = $title->getRootText();
320 if ( User
::isIP( $rootUser ) ) {
321 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
323 $user = User
::newFromName( $rootUser, false );
326 $user->load( User
::READ_NORMAL
);
328 if ( $user->isLoggedIn() ) {
329 $this->mRelevantUser
= $user;
333 return $this->mRelevantUser
;
339 * Outputs the HTML generated by other functions.
340 * @param OutputPage $out
342 abstract function outputPage( OutputPage
$out = null );
348 static function makeVariablesScript( $data ) {
350 return ResourceLoader
::makeInlineScript(
351 ResourceLoader
::makeConfigSetScript( $data )
359 * Get the query to generate a dynamic stylesheet
363 public static function getDynamicStylesheetQuery() {
364 global $wgSquidMaxage;
368 'maxage' => $wgSquidMaxage,
369 'usemsgcache' => 'yes',
370 'ctype' => 'text/css',
371 'smaxage' => $wgSquidMaxage,
376 * Add skin specific stylesheets
377 * Calling this method with an $out of anything but the same OutputPage
378 * inside ->getOutput() is deprecated. The $out arg is kept
379 * for compatibility purposes with skins.
380 * @param OutputPage $out
383 abstract function setupSkinUserCss( OutputPage
$out );
387 * @param Title $title
390 function getPageClasses( $title ) {
391 $numeric = 'ns-' . $title->getNamespace();
393 if ( $title->isSpecialPage() ) {
394 $type = 'ns-special';
395 // T25315: provide a class based on the canonical special page name without subpages
396 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
397 if ( $canonicalName ) {
398 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
400 $type .= ' mw-invalidspecialpage';
402 } elseif ( $title->isTalkPage() ) {
405 $type = 'ns-subject';
408 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
409 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
411 return "$numeric $type $name $root";
415 * Return values for <html> element
416 * @return array Array of associative name-to-value elements for <html> element
418 public function getHtmlElementAttributes() {
419 $lang = $this->getLanguage();
421 'lang' => $lang->getHtmlCode(),
422 'dir' => $lang->getDir(),
423 'class' => 'client-nojs',
428 * This will be called by OutputPage::headElement when it is creating the
429 * "<body>" tag, skins can override it if they have a need to add in any
430 * body attributes or classes of their own.
431 * @param OutputPage $out
432 * @param array $bodyAttrs
434 function addToBodyAttributes( $out, &$bodyAttrs ) {
435 // does nothing by default
448 * @return string HTML
450 function getCategoryLinks() {
451 global $wgUseCategoryBrowser;
453 $out = $this->getOutput();
454 $allCats = $out->getCategoryLinks();
456 if ( !count( $allCats ) ) {
464 $colon = $this->msg( 'colon-separator' )->escaped();
466 if ( !empty( $allCats['normal'] ) ) {
467 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
469 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
470 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
471 $title = Title
::newFromText( $linkPage );
472 $link = $title ? Linker
::link( $title, $msg ) : $msg;
473 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
474 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
478 if ( isset( $allCats['hidden'] ) ) {
479 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
480 $class = ' mw-hidden-cats-user-shown';
481 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
482 $class = ' mw-hidden-cats-ns-shown';
484 $class = ' mw-hidden-cats-hidden';
487 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
488 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
489 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
493 # optional 'dmoz-like' category browser. Will be shown under the list
494 # of categories an article belong to
495 if ( $wgUseCategoryBrowser ) {
496 $s .= '<br /><hr />';
498 # get a big array of the parents tree
499 $parenttree = $this->getTitle()->getParentCategoryTree();
500 # Skin object passed by reference cause it can not be
501 # accessed under the method subfunction drawCategoryBrowser
502 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
503 # Clean out bogus first entry and sort them
504 unset( $tempout[0] );
506 # Output one per line
507 $s .= implode( "<br />\n", $tempout );
514 * Render the array as a series of links.
515 * @param array $tree Categories tree returned by Title::getParentCategoryTree
516 * @return string Separated by >, terminate with "\n"
518 function drawCategoryBrowser( $tree ) {
521 foreach ( $tree as $element => $parent ) {
522 if ( empty( $parent ) ) {
523 # element start a new list
526 # grab the others elements
527 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
530 # add our current element to the list
531 $eltitle = Title
::newFromText( $element );
532 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
539 * @return string HTML
541 function getCategories() {
542 $out = $this->getOutput();
543 $catlinks = $this->getCategoryLinks();
545 // Check what we're showing
546 $allCats = $out->getCategoryLinks();
547 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
548 $this->getTitle()->getNamespace() == NS_CATEGORY
;
550 $classes = [ 'catlinks' ];
551 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
552 $classes[] = 'catlinks-allhidden';
555 return Html
::rawElement(
557 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
563 * This runs a hook to allow extensions placing their stuff after content
564 * and article metadata (e.g. categories).
565 * Note: This function has nothing to do with afterContent().
567 * This hook is placed here in order to allow using the same hook for all
568 * skins, both the SkinTemplate based ones and the older ones, which directly
569 * use this class to get their data.
571 * The output of this function gets processed in SkinTemplate::outputPage() for
572 * the SkinTemplate based skins, all other skins should directly echo it.
574 * @return string Empty by default, if not changed by any hook function.
576 protected function afterContentHook() {
579 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
580 // adding just some spaces shouldn't toggle the output
581 // of the whole <div/>, so we use trim() here
582 if ( trim( $data ) != '' ) {
583 // Doing this here instead of in the skins to
584 // ensure that the div has the same ID in all
586 $data = "<div id='mw-data-after-content'>\n" .
591 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
598 * Generate debug data HTML for displaying at the bottom of the main content
600 * @return string HTML containing debug data, if enabled (otherwise empty).
602 protected function generateDebugHTML() {
603 return MWDebug
::getHTMLDebugLog();
607 * This gets called shortly before the "</body>" tag.
609 * @return string HTML-wrapped JS code to be put before "</body>"
611 function bottomScripts() {
612 // TODO and the suckage continues. This function is really just a wrapper around
613 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
615 $bottomScriptText = $this->getOutput()->getBottomScripts();
616 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
618 return $bottomScriptText;
622 * Text with the permalink to the source page,
623 * usually shown on the footer of a printed page
625 * @return string HTML text with an URL
627 function printSource() {
628 $oldid = $this->getRevisionId();
630 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
631 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
633 // oldid not available for non existing pages
634 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
637 return $this->msg( 'retrievedfrom' )
638 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
643 * @return string HTML
645 function getUndeleteLink() {
646 $action = $this->getRequest()->getVal( 'action', 'view' );
648 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
649 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
650 $n = $this->getTitle()->isDeleted();
653 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
654 $msg = 'thisisdeleted';
656 $msg = 'viewdeleted';
659 return $this->msg( $msg )->rawParams(
661 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
662 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
671 * @param OutputPage $out Defaults to $this->getOutput() if left as null
674 function subPageSubtitle( $out = null ) {
675 if ( $out === null ) {
676 $out = $this->getOutput();
678 $title = $out->getTitle();
681 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
685 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
686 $ptext = $title->getPrefixedText();
687 if ( strpos( $ptext, '/' ) !== false ) {
688 $links = explode( '/', $ptext );
693 $lang = $this->getLanguage();
695 foreach ( $links as $link ) {
696 $growinglink .= $link;
698 $linkObj = Title
::newFromText( $growinglink );
700 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
701 $getlink = Linker
::linkKnown(
703 htmlspecialchars( $display )
709 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
711 $subpages .= '< ';
714 $subpages .= $getlink;
728 * @deprecated since 1.27, feature removed
729 * @return bool Always false
731 function showIPinHeader() {
732 wfDeprecated( __METHOD__
, '1.27' );
739 function getSearchLink() {
740 $searchPage = SpecialPage
::getTitleFor( 'Search' );
741 return $searchPage->getLocalURL();
747 function escapeSearchLink() {
748 return htmlspecialchars( $this->getSearchLink() );
752 * @param string $type
755 function getCopyright( $type = 'detect' ) {
756 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
758 if ( $type == 'detect' ) {
759 if ( !$this->isRevisionCurrent()
760 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
768 if ( $type == 'history' ) {
769 $msg = 'history_copyright';
774 if ( $wgRightsPage ) {
775 $title = Title
::newFromText( $wgRightsPage );
776 $link = Linker
::linkKnown( $title, $wgRightsText );
777 } elseif ( $wgRightsUrl ) {
778 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
779 } elseif ( $wgRightsText ) {
780 $link = $wgRightsText;
786 // Allow for site and per-namespace customization of copyright notice.
787 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
791 'SkinCopyrightFooter',
792 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
795 return $this->msg( $msg )->rawParams( $link )->text();
799 * @return null|string
801 function getCopyrightIcon() {
802 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
806 if ( $wgFooterIcons['copyright']['copyright'] ) {
807 $out = $wgFooterIcons['copyright']['copyright'];
808 } elseif ( $wgRightsIcon ) {
809 $icon = htmlspecialchars( $wgRightsIcon );
811 if ( $wgRightsUrl ) {
812 $url = htmlspecialchars( $wgRightsUrl );
813 $out .= '<a href="' . $url . '">';
816 $text = htmlspecialchars( $wgRightsText );
817 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
819 if ( $wgRightsUrl ) {
828 * Gets the powered by MediaWiki icon.
831 function getPoweredBy() {
832 global $wgResourceBasePath;
834 $url1 = htmlspecialchars(
835 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
837 $url1_5 = htmlspecialchars(
838 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
840 $url2 = htmlspecialchars(
841 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
843 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
844 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
845 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
846 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
851 * Get the timestamp of the latest revision, formatted in user language
855 protected function lastModified() {
856 $timestamp = $this->getOutput()->getRevisionTimestamp();
858 # No cached timestamp, load it from the database
859 if ( $timestamp === null ) {
860 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
864 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
865 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
866 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
871 if ( wfGetLB()->getLaggedReplicaMode() ) {
872 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
879 * @param string $align
882 function logoText( $align = '' ) {
883 if ( $align != '' ) {
884 $a = " style='float: {$align};'";
889 $mp = $this->msg( 'mainpage' )->escaped();
890 $mptitle = Title
::newMainPage();
891 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
893 $logourl = $this->getLogo();
894 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
900 * Renders a $wgFooterIcons icon according to the method's arguments
901 * @param array $icon The icon to build the html for, see $wgFooterIcons
902 * for the format of this array.
903 * @param bool|string $withImage Whether to use the icon's image or output
904 * a text-only footericon.
905 * @return string HTML
907 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
908 if ( is_string( $icon ) ) {
910 } else { // Assuming array
911 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
912 unset( $icon["url"] );
913 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
914 // do this the lazy way, just pass icon data as an attribute array
915 $html = Html
::element( 'img', $icon );
917 $html = htmlspecialchars( $icon["alt"] );
920 global $wgExternalLinkTarget;
921 $html = Html
::rawElement( 'a',
922 [ "href" => $url, "target" => $wgExternalLinkTarget ],
930 * Gets the link to the wiki's main page.
933 function mainPageLink() {
934 $s = Linker
::linkKnown(
935 Title
::newMainPage(),
936 $this->msg( 'mainpage' )->escaped()
943 * Returns an HTML link for use in the footer
944 * @param string $desc The i18n message key for the link text
945 * @param string $page The i18n message key for the page to link to
946 * @return string HTML anchor
948 public function footerLink( $desc, $page ) {
949 $title = $this->footerLinkTitle( $desc, $page );
954 return Linker
::linkKnown(
956 $this->msg( $desc )->escaped()
961 * @param string $desc
962 * @param string $page
965 private function footerLinkTitle( $desc, $page ) {
966 // If the link description has been set to "-" in the default language,
967 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
968 // then it is disabled, for all languages.
971 // Otherwise, we display the link for the user, described in their
972 // language (which may or may not be the same as the default language),
973 // but we make the link target be the one site-wide page.
974 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
976 return $title ?
: null;
980 * Gets the link to the wiki's privacy policy page.
981 * @return string HTML
983 function privacyLink() {
984 return $this->footerLink( 'privacy', 'privacypage' );
988 * Gets the link to the wiki's about page.
989 * @return string HTML
991 function aboutLink() {
992 return $this->footerLink( 'aboutsite', 'aboutpage' );
996 * Gets the link to the wiki's general disclaimers page.
997 * @return string HTML
999 function disclaimerLink() {
1000 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1004 * Return URL options for the 'edit page' link.
1005 * This may include an 'oldid' specifier, if the current page view is such.
1010 function editUrlOptions() {
1011 $options = [ 'action' => 'edit' ];
1013 if ( !$this->isRevisionCurrent() ) {
1014 $options['oldid'] = intval( $this->getRevisionId() );
1021 * @param User|int $id
1024 function showEmailUser( $id ) {
1025 if ( $id instanceof User
) {
1028 $targetUser = User
::newFromId( $id );
1031 # The sending user must have a confirmed email address and the target
1032 # user must have a confirmed email address and allow emails from users.
1033 return $this->getUser()->canSendEmail() &&
1034 $targetUser->canReceiveEmail();
1038 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1039 * This method returns a url resolved using the configured skin style path
1040 * and includes the style version inside of the url.
1042 * Requires $stylename to be set, otherwise throws MWException.
1044 * @param string $name The name or path of a skin resource file
1045 * @return string The fully resolved style path url including styleversion
1046 * @throws MWException
1048 function getSkinStylePath( $name ) {
1049 global $wgStylePath, $wgStyleVersion;
1051 if ( $this->stylename
=== null ) {
1052 $class = static::class;
1053 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1056 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1059 /* these are used extensively in SkinTemplate, but also some other places */
1062 * @param string $urlaction
1065 static function makeMainPageUrl( $urlaction = '' ) {
1066 $title = Title
::newMainPage();
1067 self
::checkTitle( $title, '' );
1069 return $title->getLocalURL( $urlaction );
1073 * Make a URL for a Special Page using the given query and protocol.
1075 * If $proto is set to null, make a local URL. Otherwise, make a full
1076 * URL with the protocol specified.
1078 * @param string $name Name of the Special page
1079 * @param string $urlaction Query to append
1080 * @param string|null $proto Protocol to use or null for a local URL
1083 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1084 $title = SpecialPage
::getSafeTitleFor( $name );
1085 if ( is_null( $proto ) ) {
1086 return $title->getLocalURL( $urlaction );
1088 return $title->getFullURL( $urlaction, false, $proto );
1093 * @param string $name
1094 * @param string $subpage
1095 * @param string $urlaction
1098 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1099 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1100 return $title->getLocalURL( $urlaction );
1104 * @param string $name
1105 * @param string $urlaction
1108 static function makeI18nUrl( $name, $urlaction = '' ) {
1109 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1110 self
::checkTitle( $title, $name );
1111 return $title->getLocalURL( $urlaction );
1115 * @param string $name
1116 * @param string $urlaction
1119 static function makeUrl( $name, $urlaction = '' ) {
1120 $title = Title
::newFromText( $name );
1121 self
::checkTitle( $title, $name );
1123 return $title->getLocalURL( $urlaction );
1127 * If url string starts with http, consider as external URL, else
1129 * @param string $name
1130 * @return string URL
1132 static function makeInternalOrExternalUrl( $name ) {
1133 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1136 return self
::makeUrl( $name );
1141 * this can be passed the NS number as defined in Language.php
1142 * @param string $name
1143 * @param string $urlaction
1144 * @param int $namespace
1147 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1148 $title = Title
::makeTitleSafe( $namespace, $name );
1149 self
::checkTitle( $title, $name );
1151 return $title->getLocalURL( $urlaction );
1155 * these return an array with the 'href' and boolean 'exists'
1156 * @param string $name
1157 * @param string $urlaction
1160 static function makeUrlDetails( $name, $urlaction = '' ) {
1161 $title = Title
::newFromText( $name );
1162 self
::checkTitle( $title, $name );
1165 'href' => $title->getLocalURL( $urlaction ),
1166 'exists' => $title->isKnown(),
1171 * Make URL details where the article exists (or at least it's convenient to think so)
1172 * @param string $name Article name
1173 * @param string $urlaction
1176 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1177 $title = Title
::newFromText( $name );
1178 self
::checkTitle( $title, $name );
1181 'href' => $title->getLocalURL( $urlaction ),
1187 * make sure we have some title to operate on
1189 * @param Title $title
1190 * @param string $name
1192 static function checkTitle( &$title, $name ) {
1193 if ( !is_object( $title ) ) {
1194 $title = Title
::newFromText( $name );
1195 if ( !is_object( $title ) ) {
1196 $title = Title
::newFromText( '--error: link target missing--' );
1202 * Build an array that represents the sidebar(s), the navigation bar among them.
1204 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1206 * The format of the returned array is [ heading => content, ... ], where:
1207 * - heading is the heading of a navigation portlet. It is either:
1208 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1209 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1210 * - plain text, which should be HTML-escaped by the skin
1211 * - content is the contents of the portlet. It is either:
1212 * - HTML text (<ul><li>...</li>...</ul>)
1213 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1214 * - (for a magic string as a key, any value)
1216 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1217 * and can technically insert anything in here; skin creators are expected to handle
1218 * values described above.
1222 function buildSidebar() {
1223 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1226 $callback = function () use ( $that ) {
1228 $that->addToSidebar( $bar, 'sidebar' );
1229 Hooks
::run( 'SkinBuildSidebar', [ $that, &$bar ] );
1234 if ( $wgEnableSidebarCache ) {
1235 $cache = ObjectCache
::getMainWANInstance();
1236 $sidebar = $cache->getWithSetCallback(
1237 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1238 MessageCache
::singleton()->isDisabled()
1239 ?
$cache::TTL_UNCACHEABLE
// bug T133069
1240 : $wgSidebarCacheExpiry,
1245 $sidebar = $callback();
1248 // Apply post-processing to the cached value
1249 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1255 * Add content from a sidebar system message
1256 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1258 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1261 * @param string $message
1263 public function addToSidebar( &$bar, $message ) {
1264 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1268 * Add content from plain text
1271 * @param string $text
1274 function addToSidebarPlain( &$bar, $text ) {
1275 $lines = explode( "\n", $text );
1278 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1279 ? Title
::newMainPage() : $this->getTitle();
1281 foreach ( $lines as $line ) {
1282 if ( strpos( $line, '*' ) !== 0 ) {
1285 $line = rtrim( $line, "\r" ); // for Windows compat
1287 if ( strpos( $line, '**' ) !== 0 ) {
1288 $heading = trim( $line, '* ' );
1289 if ( !array_key_exists( $heading, $bar ) ) {
1290 $bar[$heading] = [];
1293 $line = trim( $line, '* ' );
1295 if ( strpos( $line, '|' ) !== false ) { // sanity check
1296 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1297 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1298 if ( count( $line ) !== 2 ) {
1299 // Second sanity check, could be hit by people doing
1300 // funky stuff with parserfuncs... (T35321)
1306 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1307 if ( $msgLink->exists() ) {
1308 $link = $msgLink->text();
1309 if ( $link == '-' ) {
1315 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1316 if ( $msgText->exists() ) {
1317 $text = $msgText->text();
1322 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1325 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1326 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1327 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1328 $extraAttribs['rel'] = 'nofollow';
1331 global $wgExternalLinkTarget;
1332 if ( $wgExternalLinkTarget ) {
1333 $extraAttribs['target'] = $wgExternalLinkTarget;
1336 $title = Title
::newFromText( $link );
1339 $title = $title->fixSpecialName();
1340 $href = $title->getLinkURL();
1342 $href = 'INVALID-TITLE';
1346 $bar[$heading][] = array_merge( [
1349 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1362 * Gets new talk page messages for the current user and returns an
1363 * appropriate alert message (or an empty string if there are no messages)
1366 function getNewtalks() {
1368 $newMessagesAlert = '';
1369 $user = $this->getUser();
1370 $newtalks = $user->getNewMessageLinks();
1371 $out = $this->getOutput();
1373 // Allow extensions to disable or modify the new messages alert
1374 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1377 if ( $newMessagesAlert ) {
1378 return $newMessagesAlert;
1381 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1382 $uTalkTitle = $user->getTalkPage();
1383 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1385 if ( $lastSeenRev !== null ) {
1386 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1387 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1388 if ( $latestRev !== null ) {
1389 // Singular if only 1 unseen revision, plural if several unseen revisions.
1390 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1391 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1392 $lastSeenRev, $latestRev, 10, 'include_new' );
1395 // Singular if no revision -> diff link will show latest change only in any case
1398 $plural = $plural ?
999 : 1;
1399 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1400 // the number of revisions or authors is not necessarily the same as the number of
1402 $newMessagesLink = Linker
::linkKnown(
1404 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1406 [ 'redirect' => 'no' ]
1409 $newMessagesDiffLink = Linker
::linkKnown(
1411 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1413 $lastSeenRev !== null
1414 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1415 : [ 'diff' => 'cur' ]
1418 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1419 $newMessagesAlert = $this->msg(
1420 'youhavenewmessagesfromusers',
1422 $newMessagesDiffLink
1423 )->numParams( $nofAuthors, $plural );
1425 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1426 $newMessagesAlert = $this->msg(
1427 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1429 $newMessagesDiffLink
1430 )->numParams( $plural );
1432 $newMessagesAlert = $newMessagesAlert->text();
1434 $out->setCdnMaxage( 0 );
1435 } elseif ( count( $newtalks ) ) {
1436 $sep = $this->msg( 'newtalkseparator' )->escaped();
1439 foreach ( $newtalks as $newtalk ) {
1440 $msgs[] = Xml
::element(
1442 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1445 $parts = implode( $sep, $msgs );
1446 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1447 $out->setCdnMaxage( 0 );
1450 return $newMessagesAlert;
1454 * Get a cached notice
1456 * @param string $name Message name, or 'default' for $wgSiteNotice
1457 * @return string|bool HTML fragment, or false to indicate that the caller
1458 * should fall back to the next notice in its sequence
1460 private function getCachedNotice( $name ) {
1461 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1465 if ( $name === 'default' ) {
1467 global $wgSiteNotice;
1468 $notice = $wgSiteNotice;
1469 if ( empty( $notice ) ) {
1473 $msg = $this->msg( $name )->inContentLanguage();
1474 if ( $msg->isBlank() ) {
1476 } elseif ( $msg->isDisabled() ) {
1479 $notice = $msg->plain();
1482 // Use the extra hash appender to let eg SSL variants separately cache.
1483 $key = wfMemcKey( $name . $wgRenderHashAppend );
1484 $cachedNotice = $parserMemc->get( $key );
1485 if ( is_array( $cachedNotice ) ) {
1486 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1487 $notice = $cachedNotice['html'];
1496 $parsed = $this->getOutput()->parse( $notice );
1497 $parserMemc->set( $key, [ 'html' => $parsed, 'hash' => md5( $notice ) ], 600 );
1501 $notice = Html
::rawElement( 'div', [ 'id' => 'localNotice',
1502 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ], $notice );
1507 * Get the site notice
1509 * @return string HTML fragment
1511 function getSiteNotice() {
1514 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1515 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1516 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1518 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1519 if ( $anonNotice === false ) {
1520 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1522 $siteNotice = $anonNotice;
1525 if ( $siteNotice === false ) {
1526 $siteNotice = $this->getCachedNotice( 'default' );
1530 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1535 * Create a section edit link. This supersedes editSectionLink() and
1536 * editSectionLinkForOther().
1538 * @param Title $nt The title being linked to (may not be the same as
1539 * the current page, if the section is included from a template)
1540 * @param string $section The designation of the section being pointed to,
1541 * to be included in the link, like "§ion=$section"
1542 * @param string $tooltip The tooltip to use for the link: will be escaped
1543 * and wrapped in the 'editsectionhint' message
1544 * @param string $lang Language code
1545 * @return string HTML to use for edit link
1547 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1548 // HTML generated here should probably have userlangattributes
1549 // added to it for LTR text on RTL pages
1551 $lang = wfGetLangObj( $lang );
1554 if ( !is_null( $tooltip ) ) {
1555 # T27462: undo double-escaping.
1556 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1557 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1558 ->inLanguage( $lang )->text();
1563 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1564 'targetTitle' => $nt,
1565 'attribs' => $attribs,
1566 'query' => [ 'action' => 'edit', 'section' => $section ],
1567 'options' => [ 'noclasses', 'known' ]
1571 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1573 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1576 foreach ( $links as $k => $linkDetails ) {
1577 $linksHtml[] = Linker
::link(
1578 $linkDetails['targetTitle'],
1579 $linkDetails['text'],
1580 $linkDetails['attribs'],
1581 $linkDetails['query'],
1582 $linkDetails['options']
1587 '<span class="mw-editsection-divider">'
1588 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1593 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1594 // Deprecated, use SkinEditSectionLinks hook instead
1596 'DoEditSectionLink',
1597 [ $this, $nt, $section, $tooltip, &$result, $lang ],